import NodeMediaServer from 'node-media-server'
import { config } from '../../config'
import { Room } from '../../models/Room'
import logger from '../../utils/logger'

class StreamingService {
  private nms: NodeMediaServer

  constructor() {
    this.nms = new NodeMediaServer(config.media)
    this.initializeServer()
  }

  private initializeServer() {
    // 处理推流验证
    this.nms.on('prePublish', async (id, StreamPath, args) => {
      try {
        const streamKey = StreamPath.split('/')[2]
        const room = await Room.findOne({ streamKey })

        if (!room) {
          const session = this.nms.getSession(id)
          session.reject()
          return
        }

        // 更新房间状态
        room.status = 'live'
        room.startedAt = new Date()
        await room.save()

        logger.info(`Stream started: ${streamKey}`)
      } catch (error) {
        logger.error('Stream auth error:', error)
        const session = this.nms.getSession(id)
        session.reject()
      }
    })
  }

  start() {
    this.nms.run()
    logger.info('Streaming server started')
  }

  stop() {
    this.nms.stop()
    logger.info('Streaming server stopped')
  }
}

export const streamingService = new StreamingService()
